package com.xu.cloud.common.sequence;

import com.xu.cloud.common.pojo.domain.SequenceGeneratorDO;
import com.xu.cloud.common.pojo.mapper.SequenceGeneratorMapper;
import com.xu.cloud.common.util.ApplicationContextUtil;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.time.LocalDateTime;

/**
 * MySQL自增主键
 *
 * @author xuguan
 * @since 2023/12/25
 */
public class MysqlAutoIdSequence implements ISequence {

    private static final int SEQUENCE_BIT = 8;
    private static final long SEQUENCE_MAX_NUM = BigDecimal.TEN.pow(SEQUENCE_BIT).longValue() - 1;
    private static final NumberFormat fmt = new DecimalFormat("00000000");


    public synchronized long insertId() {
        SequenceGeneratorMapper sequenceGeneratorMapper = ApplicationContextUtil.getBean(SequenceGeneratorMapper.class);
        Assert.notNull(sequenceGeneratorMapper, "SequenceGeneratorMapper not allowed null");

        // 超出最大值, 重置
        long count = sequenceGeneratorMapper.selectCount(null);
        if (count >= SEQUENCE_MAX_NUM) {
            sequenceGeneratorMapper.truncate();
        }

        // 自增
        SequenceGeneratorDO insertSG = new SequenceGeneratorDO();
        LocalDateTime localDateTime = LocalDateTime.now();
        insertSG.setId(null);
        insertSG.setCreateTime(localDateTime);
        insertSG.setUpdateTime(localDateTime);
        sequenceGeneratorMapper.insert(insertSG);

        return insertSG.getId();
    }

    @Override
    public String nextId() {
        return fmt.format(this.insertId());
    }
}
